import { ref, computed, onMounted, watch } from 'vue'
import { useStorage } from '@vueuse/core'

export type Theme = 'light' | 'dark'

// 主题状态管理
const currentTheme = useStorage<Theme>('app-theme', 'light')
const systemTheme = ref<Theme>('light')

/**
 * 主题管理组合式函数
 */
export function useTheme() {
  // 检测系统主题偏好
  const detectSystemTheme = (): Theme => {
    if (typeof window !== 'undefined') {
      return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
    }
    return 'light'
  }

  // 应用主题到DOM
  const applyTheme = (theme: Theme) => {
    if (typeof document !== 'undefined') {
      const html = document.documentElement
      html.setAttribute('data-theme', theme)
      html.classList.toggle('dark', theme === 'dark')
      
      // 更新meta标签的theme-color
      const metaThemeColor = document.querySelector('meta[name="theme-color"]')
      if (metaThemeColor) {
        metaThemeColor.setAttribute('content', theme === 'dark' ? '#1f2937' : '#ffffff')
      }
    }
  }

  // 切换主题
  const toggleTheme = () => {
    currentTheme.value = currentTheme.value === 'light' ? 'dark' : 'light'
  }

  // 设置主题
  const setTheme = (theme: Theme) => {
    currentTheme.value = theme
  }

  // 计算属性
  const isDark = computed(() => currentTheme.value === 'dark')
  const isLight = computed(() => currentTheme.value === 'light')
  
  // 主题图标
  const themeIcon = computed(() => isDark.value ? 'sun' : 'moon')
  
  // 主题标签
  const themeLabel = computed(() => isDark.value ? '切换到亮色模式' : '切换到暗色模式')

  // 监听主题变化
  watch(currentTheme, (newTheme) => {
    applyTheme(newTheme)
  }, { immediate: true })

  // 监听系统主题变化
  const watchSystemTheme = () => {
    if (typeof window !== 'undefined') {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
      
      const handleChange = (e: MediaQueryListEvent) => {
        systemTheme.value = e.matches ? 'dark' : 'light'
      }
      
      mediaQuery.addEventListener('change', handleChange)
      systemTheme.value = detectSystemTheme()
      
      // 返回清理函数
      return () => mediaQuery.removeEventListener('change', handleChange)
    }
  }

  // 初始化
  onMounted(() => {
    // 检测系统主题
    systemTheme.value = detectSystemTheme()
    
    // 如果没有用户偏好，使用系统主题
    if (!localStorage.getItem('app-theme')) {
      currentTheme.value = systemTheme.value
    }
    
    // 应用初始主题
    applyTheme(currentTheme.value)
    
    // 监听系统主题变化
    watchSystemTheme()
  })

  return {
    // 状态
    currentTheme: computed(() => currentTheme.value),
    systemTheme: computed(() => systemTheme.value),
    isDark,
    isLight,
    
    // 计算属性
    themeIcon,
    themeLabel,
    
    // 方法
    toggleTheme,
    setTheme,
    applyTheme,
  }
}

/**
 * 主题配色组合式函数
 */
export function useThemeColors() {
  const { isDark } = useTheme()
  
  // 主题配色对象
  const colors = computed(() => ({
    // 背景色
    bg: {
      primary: isDark.value ? '#1f2937' : '#ffffff',
      secondary: isDark.value ? '#374151' : '#f3f4f6',
      surface: isDark.value ? '#111827' : '#f9fafb',
    },
    
    // 文字色
    text: {
      primary: isDark.value ? '#f3f4f6' : '#1f2937',
      secondary: isDark.value ? '#d1d5db' : '#6b7280',
      muted: isDark.value ? '#9ca3af' : '#9ca3af',
    },
    
    // 边框色
    border: {
      default: isDark.value ? '#4b5563' : '#e5e7eb',
      light: isDark.value ? '#374151' : '#f3f4f6',
    },
    
    // 状态色
    status: {
      success: isDark.value ? '#10b981' : '#059669',
      warning: isDark.value ? '#f59e0b' : '#d97706',
      error: isDark.value ? '#ef4444' : '#dc2626',
      info: isDark.value ? '#3b82f6' : '#2563eb',
    },
  }))
  
  return {
    colors,
    isDark,
  }
}

/**
 * 响应式断点组合式函数
 */
export function useBreakpoints() {
  const breakpoints = {
    sm: 640,
    md: 768,
    lg: 1024,
    xl: 1280,
    '2xl': 1536,
  }
  
  const windowWidth = ref(typeof window !== 'undefined' ? window.innerWidth : 1024)
  
  // 当前断点
  const currentBreakpoint = computed(() => {
    const width = windowWidth.value
    if (width >= breakpoints['2xl']) return '2xl'
    if (width >= breakpoints.xl) return 'xl'
    if (width >= breakpoints.lg) return 'lg'
    if (width >= breakpoints.md) return 'md'
    if (width >= breakpoints.sm) return 'sm'
    return 'xs'
  })
  
  // 断点检查函数
  const isSmAndUp = computed(() => windowWidth.value >= breakpoints.sm)
  const isMdAndUp = computed(() => windowWidth.value >= breakpoints.md)
  const isLgAndUp = computed(() => windowWidth.value >= breakpoints.lg)
  const isXlAndUp = computed(() => windowWidth.value >= breakpoints.xl)
  const is2xlAndUp = computed(() => windowWidth.value >= breakpoints['2xl'])
  
  const isMobile = computed(() => windowWidth.value < breakpoints.md)
  const isTablet = computed(() => windowWidth.value >= breakpoints.md && windowWidth.value < breakpoints.lg)
  const isDesktop = computed(() => windowWidth.value >= breakpoints.lg)
  
  // 监听窗口大小变化
  const updateWindowWidth = () => {
    if (typeof window !== 'undefined') {
      windowWidth.value = window.innerWidth
    }
  }
  
  onMounted(() => {
    if (typeof window !== 'undefined') {
      window.addEventListener('resize', updateWindowWidth)
    }
  })
  
  return {
    // 断点值
    breakpoints,
    windowWidth: computed(() => windowWidth.value),
    currentBreakpoint,
    
    // 断点检查
    isSmAndUp,
    isMdAndUp,
    isLgAndUp,
    isXlAndUp,
    is2xlAndUp,
    
    // 设备类型
    isMobile,
    isTablet,
    isDesktop,
  }
}
